package com.zb777.shuzhilingxi.controller;


import com.zb777.shuzhilingxi.Pojo.dto.RefreshTokenRequest;
import com.zb777.shuzhilingxi.Pojo.dto.UserDTO;
import com.zb777.shuzhilingxi.Pojo.dto.UserLoginDTO;
import com.zb777.shuzhilingxi.Pojo.entity.User;
import com.zb777.shuzhilingxi.Pojo.vo.UserLoginVO;
import com.zb777.shuzhilingxi.constant.JwtClaimsConstant;
import com.zb777.shuzhilingxi.properties.JwtProperties;
import com.zb777.shuzhilingxi.result.Result;
import com.zb777.shuzhilingxi.service.IUserService;
import com.zb777.shuzhilingxi.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-07-10
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户接口")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result register(@RequestBody UserDTO userDTO)
    {

        log.info("用户注册:{}", userDTO);
        return userService.register(userDTO);
    }
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录:{}", userLoginDTO);
        User user=userService.login(userLoginDTO);
        log.info("用户登录成功:{}", user);
        // 根据remember参数设置不同的过期时间
        Boolean remember = userLoginDTO.getRememberMe();
        int accessExpiration = remember ? 7 * 24 * 60 * 60 * 1000 : 2 * 60 * 60 * 1000; // 7天或2小时
        int refreshExpiration = remember ? 14 * 24 * 60 * 60 * 1000 : 24 * 60 * 60 * 1000; // 14天或1天
        //登录成功后，生成jwt令牌
        Map<String, Object> claims1 = new HashMap<>();
        claims1.put(JwtClaimsConstant.USER_ID, user.getUserId());
        String accessToken = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                accessExpiration,
                claims1);
        Map<String, Object> claims2 = new HashMap<>();
        claims2.put(JwtClaimsConstant.USER_ID, user.getUserId());
        String refreshToken = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                refreshExpiration,
                claims2);


        UserLoginVO userLoginVO =UserLoginVO.builder()
                .userId(user.getUserId())
                .userName(user.getUsername())
                .profilePicture(user.getProfilePicture())
                .tokenBalance(user.getTokenBalance())
                .accessToken(accessToken)
                .refreshToken(refreshToken)
                .build();
        log.info("用户登录成功:{}", userLoginVO);

        return Result.success(userLoginVO);
    }

    @GetMapping("/verify-token")
    public ResponseEntity<?> verifyToken(HttpServletRequest request) {
        // 从请求头中获取Authorization字段
        String authHeader = request.getHeader("Authorization");

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("valid", false, "message", "缺少令牌"));
        }

        // 提取JWT（去掉Bearer前缀）
        String token = authHeader.substring(7);

        try {
            // 使用JwtUtil解析令牌
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);

            // 获取过期时间
            Date expiration = claims.getExpiration();
            boolean isValid = expiration.after(new Date());

            return ResponseEntity.ok(Map.of("valid", isValid));
        } catch (Exception e) {
            // 处理各种JWT异常
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("valid", false, "message", "无效的令牌: " + e.getMessage()));
        }
    }

    @PostMapping("/refresh")
    public ResponseEntity<?> refreshToken(@RequestBody RefreshTokenRequest request) {
        String refreshToken = request.getRefreshToken();
        Boolean remember = request.getRemember() != null ? request.getRemember() : false;

        if (refreshToken == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("message", "缺少刷新令牌"));
        }

        try {
            // 验证刷新令牌
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), refreshToken);

            // 从claims中获取用户身份信息
            Long userId = (Long) claims.get(JwtClaimsConstant.USER_ID); // 根据你的JWT设置调整
            User user = userService.SelectByUserId(userId);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(Map.of("message", "用户不存在"));
            }

            // 设置新的访问令牌过期时间
            int accessExpiration = remember ?
                    7 * 24 * 60 * 60 * 1000 : // 7天
                    2 * 60 * 60 * 1000;      // 2小时

            // 创建新的访问令牌
            Map<String, Object> claimsMap = new HashMap<>();
            claimsMap.put(JwtClaimsConstant.USER_ID, user.getUserId());
            // 添加其他需要的claims...

            String newAccessToken = JwtUtil.createJWT(
                    jwtProperties.getSecretKey(),
                    accessExpiration,
                    claimsMap
            );

            return ResponseEntity.ok(Map.of(
                    "access_token", newAccessToken,
                    "message", "令牌刷新成功"
            ));
        } catch (ExpiredJwtException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("message", "刷新令牌已过期"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("message", "无效的刷新令牌: " + e.getMessage()));
        }
    }
    @PostMapping("/logout")
    @Operation(summary = "用户登出")
    public Result<?> logout(HttpServletRequest request) {
        // 1. 从请求头获取令牌（可选：验证令牌是否有效）
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            try {
                // 验证令牌是否有效（可选步骤，仅为了确认登出的是有效用户）
                JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            } catch (Exception e) {
                // 令牌无效时仍允许登出（客户端可能存储了过期令牌）
                log.warn("登出时令牌无效: {}", e.getMessage());
            }
        }

        // 2. 登出成功（实际清除逻辑由客户端完成）
        return Result.success("成功登出");
    }
}
